const express = require('express');
const { DBHOST, PORT } = require('./config/config');
const db = require('./db/db');
const path = require('path');
const userRoutes = require('./routes/userRoute');
const uploads = require('./routes/uploads');
const chatRoutes = require('./routes/chatRoute')
const Chat = require('./models/chatModel');
const User = require('./models/userModel')
const cors = require('cors');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: 'http://localhost:5173',  // 允许来自这个 origin 的请求
    methods: ['GET', 'POST'],         // 允许的 HTTP 方法
    allowedHeaders: ['Content-Type'], // 允许的请求头
    credentials: true                 // 如果有需要的话，可以设置为 true，表示允许跨域请求携带凭据（cookies等）
  }
});
const FriendshipModel = require('./models/friendshipfModel')
app.use(express.json()); // 使用 express 内建的 json 解析中间件
app.use(express.urlencoded({ extended: true }));

// 设置静态文件夹，确保上传的文件可以通过 URL 访问
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 连接数据库
db(
  () => {
    console.log('数据库连接成功');
    // 启动服务器
    server.listen(PORT, () => {
      console.log(`服务器正在运行,访问地址 http://${DBHOST}:${PORT}`);
    });
  },
  (err) => {
    console.error('数据库连接失败', err);
    process.exit(1); // 如果连接失败，退出进程
  }
);

// 使用路由
app.use('/user', userRoutes);
app.use('/img', uploads)
app.use('/chat', chatRoutes)
// 启用 CORS
app.use(cors());


// // // 在服务器端处理聊天消息
// io.on('connection', (socket) => {
//   console.log('New client connected');

//   socket.on('chat message', async (msg) => {
//     const sender = await User.findById(msg.senderId);
//     const receiver = await User.findById(msg.receiverId);
//     console.log(msg);

//     if (sender && receiver) {
//       // 存储聊天记录
//       const chatRecord = new Chat({
//         senderId: msg.senderId,
//         receiverId: msg.receiverId,
//         content: msg.content,
//         timestamp: new Date()
//       });
//       await chatRecord.save();
//     }


//     // 查询未读消息数量
//     const unreadCountSender = await Chat.countDocuments({
//       senderId: msg.receiverId,
//       receiverId: msg.senderId,
//       isRead: false
//     });

//     const unreadCountReceiver = await Chat.countDocuments({
//       senderId: msg.senderId,
//       receiverId: msg.receiverId,
//       isRead: false
//     });
//     console.log(unreadCountReceiver);
//     console.log(unreadCountSender);

//     // 广播消息到所有客户端
//     io.emit('chat message', {
//       msg,
//       unreadCountSender,        // 未读消息数量（对于sender）
//       unreadCountReceiver
//     });
//   });
//   // 监听断开连接
//   socket.on('disconnect', () => {
//     console.log('Client disconnected');
//   });
// });
io.on('connection', (socket) => {
  console.log('A user connected: ' + socket.id);

  // 监听用户加入房间
  socket.on('joinRoom', ({ userId, roomName }) => {
      socket.join(roomName);
      console.log(`${userId} joined room: ${roomName}`);
  });

  // 监听消息发送
  socket.on('sendMsg', async(msg) => {
    // console.log(msg);

    // 将消息存入到数据库里
       // 将消息存储到数据库
      //  修改:添加房间号roomName,保存到聊天记录数据库中
       const chatRecord = new Chat({
        senderId: msg.message.senderId,
        receiverId: msg.message.receiverId,
        content: msg.message.content,
        timestamp: msg.message.timestamp || new Date(),  // 使用传来的时间戳或当前时间
        isRead: false,  // 默认消息未读
        roomName:msg.roomName
      });
  
      try {
        await chatRecord.save(); // 保存消息到数据库
        console.log('Chat record saved:', chatRecord);
      } catch (error) {
        console.error('Error saving chat record:', error);
      }
      // 将消息发送到房间
  
      io.to(msg.roomName).emit('receiveMsg', msg);
  });

  // 监听用户断开连接
  socket.on('disconnect', () => {
      console.log('A user disconnected: ' + socket.id);
  });
});